/**
 * @description 文章列表控制器
 * @author 韩
 */

const { randomUUID } = require("crypto")
const model = require("../../../model/context/article/ARTICLE.MODEL")
const { getFilter } = require("../../../utils/setFilter")
const dayjs = require("dayjs")
const { addRecord, deleteRecord } = require("../subject/realtion_subject&article")

// 创建一个内容
const controller_save = async ({
    id = undefined,
    title = undefined,
    subjectId = undefined,
    intro = undefined,
    masterImage = undefined,
    description = undefined,
    status = "1",
    seoDescription = undefined,
    seoTitle = undefined,
    urlname = undefined,
    keyWords = undefined,

}) => {
    try {
        const params = {
            id, title, intro, masterImage, description, status,
            seoDescription,
            seoTitle,
            urlname,
            keyWords,
        }
        let addRes = null;
        if (!id) {
            // 添加创建
            addRes = await model.create({
                createDate: dayjs().format("YYYY-MM-DD HH:mm:ss"),
                ...params,
                id: randomUUID(),
            })
        } else {
            // 更新修改
            addRes = await model.findOneAndUpdate({ id: id }, {
                $set: {
                    ...params
                }
            }, { new: true })
        }

        if (addRes) {
            const {
                id, title, intro, masterImage, description, status, createDate,
                seoDescription,
                seoTitle,
                urlname,
                keyWords,
            } = addRes
            console.log("文章保存结果：", id);
            // 如果有选择分类，保存文章的分类
            subjectId && await addRecord({
                subjectId: subjectId,
                articleId: id
            })

            return {
                code: 0,
                msg: "成功",
                data: {
                    id, title, intro, subjectId, masterImage: JSON.parse(masterImage), description, status, createDate,
                    seoDescription,
                    seoTitle,
                    urlname,
                    keyWords,
                }
            }
        }
        return {
            code: 100,
            msg: "失败",
        }
    } catch (error) {
        console.log("程序错误：", error)
        return {
            code: 1332,
            msg: "程序错误"
        }
    }
}


// 查询列表 
const controller_find = async ({ title = undefined, status = undefined, current, pageSize, }) => {

    let params = {
        title, status,
        deleteFlag: false
    }
    let filter = getFilter(params)

    // /**
    //  * @description 聚合查询
    //  * 
    //  */
    const totalCount = await model.countDocuments({ ...filter, deleteFlag: false });

    const queryList = await model.aggregate([
        {
            $match: {
                ...filter,
                deleteFlag: false
            }
        },
        { $sort: { sort: 1 } },
        { $skip: (current - 1) * pageSize },
        { $limit: pageSize },
        {
            $lookup: {
                from: "correlation_tab_subject&articles",
                let: { articleId: "$id" },
                pipeline: [
                    {
                        $match: {
                            $expr: { $eq: ["$articleId", "$$articleId"] }
                        }
                    },
                    { $project: { subjectId: 1 } }
                ],
                as: "subjectData"
            }
        },
        {
            $unwind: {
                path: "$subjectData",
                preserveNullAndEmptyArrays: true
            }
        },
        {
            //添加字段
            $addFields: {
                subjectId: { $ifNull: ["$subjectData.subjectId", null] }
            }
        },
        {
            //删除字段
            $project: {
                subjectData: 0
            }
        }
    ]);

    return {
        code: 0,
        msg: "查询成功",
        data: {
            totalCount,
            list: queryList
        }

    }
}


/**@description 根据id查详情 */
const controller_get = async ({ id, title }) => {
    try {


        /**
         * @description 聚合查询
         */
        const res = await model.aggregate([
            {
                $match: {
                    id
                }
            },
            {
                $lookup: {
                    from: "correlation_tab_subject&articles",
                    localField: "id", //文章表中的id去匹配关联表中的articleId
                    foreignField: "articleId", //去匹配关联表中的articleId
                    as: "categoryInfo"//返回结果存放到subjectId
                }
            },

        ])
        if (res && res.length === 1) {
            // console.log("产品详情查询：", res);
            const { id, title, categoryInfo, masterImage, description, status, intro, createDate, seoDescription,
                seoTitle,
                urlname,
                keyWords, } = res[0];

            return {
                code: 0,
                msg: "查询成功",
                data: {
                    id, title, subjectId: categoryInfo[0]?.subjectId || undefined, masterImage: JSON.parse(masterImage), description, status, intro, createDate, seoDescription,
                    seoTitle,
                    urlname,
                    keyWords,
                }
            }
        } else {
            return {
                code: 100,
                msg: "未找到对应文章数据"
            }
        }
    } catch (error) {
        console.log("查详情报错：", error)
    }
}

// 删除
const controller_delete = async ({ id = undefined, action = "delete" }) => {
    try {
        let res = null;
        if (action === "delete") {
            // 逻辑删除
            res = await model.findOneAndUpdate({ id: id }, {
                $set: {
                    deleteFlag: true
                }
            }, { new: true })
        } else {
            //物理删除
            res = await model.deleteMany({
                id: { $in: id }
            });
        }
        if (res) {
            action === "clear" && await deleteRecord({
                articleId: id && { $in: id }
            })
            return {
                code: 0,
                msg: `删除成功`
            }
        } else {
            return {
                code: 100,
                msg: `删除失败`
            }
        }
    } catch (error) {
        console.log("删除控制器出错", error)
    }

}
module.exports = {
    controller_save,
    controller_find,
    controller_get,
    controller_delete,
}